<template>
    <canvas id="canvas"></canvas>
</template>

<script setup lang="ts">
  import {onMounted} from "vue";
  import RenderContext from "@/views/cg/lib/RenderContext.ts";
  import {Model, shape, matrix } from '../lib'

  onMounted(()=>{

    let gl = RenderContext.getGL()
    // 绘制一个model
    const mesh = shape.d3_f()
    console.log(mesh)
    const model = new Model(mesh)
    // 绘制多个model
    // const models = []
    // const mesh = shape.d3_f()
    // for(let i=0;i<10;i++){
    //   models.push(new Model(mesh))
    // }

    let angle = 0.0
    const aspect = gl.canvas.width/gl.canvas.height;
    function draw() {

      // 开启深度测试
      gl.enable(gl.DEPTH_TEST);
      gl.depthFunc(gl.LEQUAL)
      // 每次画的时候 画布都设置成最大的深度，深度值越小 权重越高
      gl.clearDepth(1.0)
      gl.viewport(0.0, 0.0, canvas.width, canvas.height)
      // 清空屏幕
      gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)

      // 绘制一个model
      let world = matrix.identity4d()
      world = matrix.multiply4(world, matrix.scale3d(2/210, -2/210, 2/210))
      // 往Z方向移动一点
      world = matrix.multiply4(world, matrix.translate3d(0, 0, -3))
      // 加上旋转矩阵
      world = matrix.multiply4(world, matrix.rotateY(0.2*Math.PI))
      // 还可以加上x轴旋转
      world = matrix.multiply4(world, matrix.rotateX(0.05*Math.PI))
      // 加上透视投影
      world = matrix.multiply4(world, matrix.perspective(
        Math.PI * 0.5,
        aspect,
        1.0,
        1000
      ))
      model.setWorldMatrix(world)
      angle += 0.01
      model.draw()

      // 如果绘制多个model
      /*for(let i=0;i<10;i++){
        const model = models[i]
        let world = matrix.identity4d()
        world = matrix.multiply4(world, matrix.scale3d(2/210, -2/210, 2/210))
        // 往Z方向移动一点 -10 往里退一下视角
        world = matrix.multiply4(world, matrix.translate3d(0, 0, -1))
        // 加上旋转矩阵 每个F 都绕着 Y转 加上angle
        world = matrix.multiply4(world, matrix.rotateY(angle + 0.2*Math.PI * i / 10))
        // 加上透视投影
        world = matrix.multiply4(world, matrix.perspective(
          Math.PI * 0.5,
          aspect,
          1.0,
          1000
        ))
        model.setWorldMatrix(world)
      }

      angle += 0.01
      for(let i=0;i<10;i++){
        models[i].draw()
      }
     */

      requestAnimationFrame(draw)
    }
    draw()
  })
</script>

<style scoped lang="scss">
#canvas{
  width: 100%;
  height: 100%;
  display: block;
}
</style>
